import React, { useEffect, useState } from 'react'
import { Button, Space, Drawer, DatePicker, Form, Input  } from 'antd';
import axios from '../../aixos';
import moment from 'moment'
import Table from '../../components/Table/Table'

const { TextArea } = Input;

export default function Mood() {
  const columns = [
    {
      title: '内容',
      dataIndex: 'content',
    },
    {
      title: '引用',
      dataIndex: 'quote',
      render: text => <span>{text}</span>,
    },
    {
      title: '作者',
      dataIndex: 'author',
      render: text => <span>{text}</span>,
    },
    {
      title: '发布时间',
      dataIndex: 'publishDate',
      render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    // {
    //   title: '操作',
    //   render: (_, record) => (
    //     <Space size="middle">
    //       <Button type='primary' onClick={() => edit(record)}>编辑</Button>
    //       <Button type='danger' onClick={() => del(record._id)}>删除</Button>
    //     </Space>
    //   ),
    // },
  ];


  const [visible, setVisible] = useState(false);
  const [drawerTitle, setDrawerTitle] = useState('')
  const [moodList, setMoodList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageIndex, setPageIndex] = useState(1)
  const pageSize = 10
  const [editRecordId, setEditRecordId] = useState(null)
  
  useEffect(() => {
    axios.get('/mood', {
      pageIndex,
      pageSize
    }).then(res => {
      setMoodList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])
  const changePage = (index) => {
    setPageIndex(index)
  }
  const onClose = () => {
    setVisible(false);
  };
  const edit = (record) => {
    setEditRecordId(record._id)
    console.log(moment(record.publishDate))
    console.log(moment(record.publishDate).format('YYYY-MM-DD HH:mm:ss'))
    setDrawerTitle('编辑')
    console.log(record)
    console.log(form)
    form.setFieldsValue({
      publishDate: moment(record.publishDate),
      content: record.content,
      author: record.author,
      quote: record.quote
    })
    setVisible(true);
  }
  const add = () => {
    form.resetFields()
    setDrawerTitle('添加')
    setVisible(true);
  }
  const del = (id) => {
    axios.delete('/mood', {
      id
    }).then(() => {
      setMoodList(moodList.filter(item => item._id !== id))
    })
  }
  const submit = async () => {
    const formData = await form.validateFields()
    console.log(formData)
    if (!editRecordId) {
      axios.post('/mood', formData).then(res => {
        setMoodList([res.data, ...moodList])
        setVisible(false);
      })
    } else {
      axios.put('/mood', {
        id: editRecordId,
        ...formData
      }).then(res => {
        console.log(res)
        setMoodList(moodList.map(item => {
          if (item._id === editRecordId) return { ...item, ...formData } 
          return item
        }))
        setVisible(false);
      })
    }
  }

  function onChange(value, dateString) {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
  }
  
  function onOk(value) {
    console.log('onOk: ', value);
  }
  const [form] = Form.useForm();
  return (
    <div>
      <Table rowKey='_id' columns={columns} dataSource={moodList} pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 条数据`,
        onChange: changePage
      }} 
      action={{
        edit: {callback: edit},
        delete: {callback: del}
      }}
      >
        <Button type='primary' onClick={add}>发布新心情</Button>
      </Table>
      <Drawer title={drawerTitle} placement="right" size='large' onClose={onClose} visible={visible}
        extra={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={submit}>
              提交
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="发布日期"
            name="publishDate"
          >
            <DatePicker format='YYYY-MM-DD hh:mm:ss' showTime onChange={onChange} onOk={onOk} />
          </Form.Item>
          <Form.Item
            label="发布内容"
            name="content"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <TextArea rows={6} placeholder="请输入内容" />
          </Form.Item>
          <Form.Item
            label="引用"
            name="quote"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="作者"
            name="author"
          >
            <Input />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}
